package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.util.IdGenerator;
import team.bluepen.supermarket.util.ServletUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Kai
 */
@WebServlet(name = "IdRedirectServlet", urlPatterns = "/api/id-redirect")
public class IdRedirectServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestSource = ServletUtil.getRefererUrl(req);
        String id = req.getParameter("new_id");
        IdGenerator.redirectId(Math.max(Integer.parseInt(id), 1));

        resp.sendRedirect(requestSource);
    }
}
